//
//  CZEmoticonKeyBoard.swift
//  Weibo30
//
//  Created by apple on 16/8/17.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
//  表情键盘自定义视图
/*
    1. 表情视图 -> UICollectionView
    2. toolBar视图 -> UIStackView
*/
//  重用标记
private let EmoticonCollectionViewCellIdentifier = "EmoticonCollectionViewCellIdentifier"

class CZEmoticonKeyBoard: UIView {

    //  MARK: -- 懒加载控件
    private lazy var toolBar: CZEmoticonToolBar = {
        let toolBar = CZEmoticonToolBar(frame: CGRectZero)
        return toolBar
    }()
    
    //  表情视图
    private lazy var emoticonCollectionView: UICollectionView = {
        
        let flowLayout = UICollectionViewFlowLayout()
        //  设置水平方向滚动
        flowLayout.scrollDirection = .Horizontal
        
        let view = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout)
        view.backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        //  设置水平和垂直方向的滚动指示器不显示
        view.showsHorizontalScrollIndicator = false
        view.showsVerticalScrollIndicator = false
        //  开启分页
        view.pagingEnabled = true
        //  不开启弹簧效果
        view.bounces = false
        
        //  注册cell
        view.registerClass(CZEmoticonCollectionViewCell.self, forCellWithReuseIdentifier: EmoticonCollectionViewCellIdentifier)
        //  数据源代理
        view.dataSource = self
        //  设置代理
        view.delegate = self
        
        return view
    
    }()
    
    //  页数指示器
    private lazy var pageControl: UIPageControl = {
    
        let pageCtr = UIPageControl()
        pageCtr.currentPageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_selected")!)
        pageCtr.pageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_normal")!)
        
        return pageCtr
        
        
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
    
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        
        //  默认页数数据绑定
        let defaultIndexPath: NSIndexPath = NSIndexPath(forItem: 0, inSection: 0)
        //  设置数据
        setPageControlDataForIndexPath(defaultIndexPath)
        
        addSubview(emoticonCollectionView)
        //  添加页数指示控件
        addSubview(pageControl)
        //  添加控件
        addSubview(toolBar)
        
        //  设置约束
        
        emoticonCollectionView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self)
            make.leading.equalTo(self)
            make.trailing.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        pageControl.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(emoticonCollectionView)
            make.centerX.equalTo(emoticonCollectionView)
            make.height.equalTo(10)
        }
        
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self)
            make.leading.equalTo(self)
            make.trailing.equalTo(self)
            make.height.equalTo(35)
        }
        
        toolBar.didSeletedButtonClosure = { [weak self] (type: CZEmoticonToolBarButtonType) in
            
            //  滚动到的indexPath
            let indexPath: NSIndexPath
            switch type {
            case .Normal:
                print("默认")
                indexPath = NSIndexPath(forItem: 0, inSection: 0)
            case .Emoji:
                print("emoji")
                indexPath = NSIndexPath(forItem: 0, inSection: 1)
            case .LXH:
                print("LXH")
                indexPath = NSIndexPath(forItem: 0, inSection: 2)
            
            }
            
            //  滚动到指定位置,不需要开启动画
            self?.emoticonCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
            
            
            self?.setPageControlDataForIndexPath(indexPath)
            
            
        }
        
    }
    //  通过indexPath绑定页数控件的数据
    private func setPageControlDataForIndexPath(indexPath: NSIndexPath) {
        pageControl.numberOfPages = CZEmoticonTools.sharedTools.allEmoticonArray[indexPath.section].count
        pageControl.currentPage = indexPath.item
    
    }
    
   
    //  设置子控件布局方式
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let flowLayout = emoticonCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        //  设置每项的大小
        flowLayout.itemSize = emoticonCollectionView.size
        //  设置水平间距和垂直间距
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
    }
    
    

}


extension CZEmoticonKeyBoard: UICollectionViewDataSource, UICollectionViewDelegate {
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return CZEmoticonTools.sharedTools.allEmoticonArray.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return CZEmoticonTools.sharedTools.allEmoticonArray[section].count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonCollectionViewCellIdentifier, forIndexPath: indexPath) as! CZEmoticonCollectionViewCell
        
        //  设置绑定数据
        cell.emoticons = CZEmoticonTools.sharedTools.allEmoticonArray[indexPath.section][indexPath.item]
        
        
        return cell
    }
    //  监听collectionView的滚动
    func scrollViewDidScroll(scrollView: UIScrollView) {
//        print(scrollView.contentOffset.x)
        //  获取当前屏幕显示的cell, 获取的cell不会对其进行x坐标排序,随机返回的
        let cells = emoticonCollectionView.visibleCells().sort { (firstCell, secondCell) -> Bool in
            return firstCell.x < secondCell.x
        }
        //  判断哪个cell显示多
        if cells.count == 2 {
            //  获取第一个cell
            let firstCell = cells.first!
            //  获取第二个cell
            let secondCell = cells.last!
            
            
//            print("第一个cell: \(firstCell)")
//            print("第二个cell: \(secondCell)")
            //  通过差值的计算,判断哪个cell显示多
            //  第一个偏移量差值(只想关心偏移的差值多少)
            let firstContentOffSetX = abs(firstCell.x - scrollView.contentOffset.x)
            //  第二个偏移量差值
            let secondContentOffSetX = secondCell.x - scrollView.contentOffset.x
//            print("第一个差值\(firstContentOffSetX)")
//            print("第二个差值\(secondContentOffSetX)")
            //  记录哪个cell显示的多
            let cell: UICollectionViewCell
            if firstContentOffSetX < secondContentOffSetX {
//                print("第一个cell显示多")
                cell = firstCell
            } else {
//                print("第二个cell显示多")
                cell = secondCell
            }
            
            //  根据cell获取对应的indexPath
            let indexPath = emoticonCollectionView.indexPathForCell(cell)!
            
            //  获取indexPath对应的是哪个一组
            let section = indexPath.section
            //  选中指定这组数据
            toolBar.selectedButtonWithSection(section)
            
            setPageControlDataForIndexPath(indexPath)
            
        }
      
        
        
    }
    
    
    

}










